package com.system.borrow.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.system.borrow.Constant.URLDefind;
import com.system.borrow.R;
import com.system.borrow.bean.CustomerDTO;
import com.system.borrow.bean.GloData;
import com.system.borrow.cache.CacheMode;
import com.system.borrow.callback.DialogCallback;
import com.system.borrow.fragment.MyFragment;
import com.system.borrow.http.model.HttpParams;
import com.system.borrow.http.utils.OkHttpUtils;
import com.system.borrow.utils.SecondTitle;
import com.system.borrow.utils.SharedPreferencesUtil;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 登录
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {
    LinearLayout ll_login, ll_nopwd;
    TextView tv_login, tv_nopwd, forget_pwd, tv_code;
    int type = 0;//0  账号登录    1无密码登录
    TextView tv_right;
    private Button btn_login;
    private EditText et_login_mobile, et_login_code, et_mobile, et_code;
    private TimeCount time;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        SecondTitle title = new SecondTitle(this);
        title.setTitle("登录", "注册");
        time = new TimeCount(60000, 1000);
        tv_right = title.tv_right;
        initView();
        initListener();
    }

    private void initListener() {
        tv_login.setOnClickListener(this);
        tv_nopwd.setOnClickListener(this);
        forget_pwd.setOnClickListener(this);
        tv_right.setOnClickListener(this);
        tv_code.setOnClickListener(this);
        btn_login.setOnClickListener(this);
    }

    private void initView() {
        ll_login = (LinearLayout) findViewById(R.id.ll_login);
        ll_nopwd = (LinearLayout) findViewById(R.id.ll_nopwd);
        tv_login = (TextView) findViewById(R.id.tv_login);
        tv_nopwd = (TextView) findViewById(R.id.tv_nopwd);
        forget_pwd = (TextView) findViewById(R.id.forget_pwd);

        //在选择账户密码登录的时候获取
        et_login_mobile = (EditText) findViewById(R.id.et_login_mobile);
        et_login_code = (EditText) findViewById(R.id.et_login_code);

        //在选择动态登陆的时候获取
        et_mobile = (EditText) findViewById(R.id.et_mobile);
        et_code = (EditText) findViewById(R.id.et_code);
        tv_code = (TextView) findViewById(R.id.tv_code);

        btn_login = (Button) findViewById(R.id.btn_login);

        tv_login.setSelected(true);
        tv_nopwd.setSelected(false);
        ll_login.setVisibility(View.VISIBLE);
        ll_nopwd.setVisibility(View.GONE);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_login:
                type = 0;
                tv_login.setSelected(true);
                tv_nopwd.setSelected(false);
                ll_login.setVisibility(View.VISIBLE);
                ll_nopwd.setVisibility(View.GONE);
                break;
            case R.id.tv_nopwd:
                type = 1;
                tv_login.setSelected(false);
                tv_nopwd.setSelected(true);
                ll_login.setVisibility(View.GONE);
                ll_nopwd.setVisibility(View.VISIBLE);
                break;
            case R.id.forget_pwd:
                Intent pwd_intent = new Intent(this, MobileActivity.class);
                startActivity(pwd_intent);
                break;
            case R.id.tv_right:
                Intent intent = new Intent(this, RegisterActivity.class);
                startActivity(intent);
                finish();
                break;
            case R.id.btn_login:
                if (type == 0) {
                    String mobile = et_login_mobile.getText().toString().trim();
                    String passWord = et_login_code.getText().toString().trim();
                    if (mobile.isEmpty()) {
                        ToastShow("请输入手机号码!");
                    } else {
                        if (passWord.isEmpty()) {
                            ToastShow("请输入密码");
                        } else {
                            login(mobile, passWord);
                        }
                    }
                } else {
                    String mobile = et_mobile.getText().toString().trim();
                    String code = et_code.getText().toString().trim();
                    if (mobile.isEmpty()) {
                        ToastShow("请输入手机号码!");
                    } else {
                        if (code.isEmpty()) {
                            ToastShow("请输入验证码");
                        } else {
                            login(mobile, code);
                        }
                    }
                }
                break;
            case R.id.tv_code:
                String mobile = et_mobile.getText().toString().trim();
                if (mobile.isEmpty()) {
                    ToastShow("请输入手机号码!");
                } else {
                    time.start();
                    getCode(mobile);
                }
                break;
        }
    }

    /**
     * 获取验证码
     *
     * @param mobile
     */
    private void getCode(String mobile) {
        HttpParams params = new HttpParams();
        params.put("mobile", mobile);
        params.put("type", "2");
        OkHttpUtils.post(URLDefind.SEND_CODE)
                .tag(this)
                .params(params)
                .cacheMode(CacheMode.NO_CACHE)
                .execute(new DialogCallback<String>(this, String.class, null) {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        try {
                            JSONObject json = new JSONObject(s);
                            int statusCode = json.getInt("statusCode");
                            if (statusCode == 200) {
                                ToastShow("短信已发送,请注意查收");
                            } else {
                                ToastShow(json.getString("message"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onCacheResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {

                    }

                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                });
    }

    /**
     * 登陆
     *
     * @param mobile
     * @param password
     */
    private void login(String mobile, String password) {
        HttpParams params = new HttpParams();
        if (type == 0) {
            params.put("mobile", mobile);
            params.put("password", password);
        } else {
            params.put("mobile", mobile);
            params.put("code", password);
        }
        OkHttpUtils.post(URLDefind.LOGIN)
                .tag(this)
                .params(params)
                .cacheMode(CacheMode.NO_CACHE)
                .execute(new DialogCallback<String>(this, String.class, null) {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            int statusCode = jsonObject.getInt("statusCode");
                            Gson gson = new Gson();
                            if(statusCode ==200){
                                String data = jsonObject.getString("data");
                                TypeToken<CustomerDTO> token = new TypeToken<CustomerDTO>(){};
                                final CustomerDTO customer = gson.fromJson(data,token.getType());
                                GloData.setCustomerDTO(customer);
                                if(MyFragment.myFragment!=null){
                                    MyFragment.myFragment.loadData();
                                }
                                SharedPreferencesUtil.putString(LoginActivity.this,"custormer","custormer",gson.toJson(customer));
                                finish();
                            }else{
                                ToastShow(jsonObject.getString("message"));
                            }

                        }catch (JSONException e){
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onCacheResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {

                    }

                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                });
    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {// 计时完毕
            tv_code.setText("获取");
            tv_code.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程
            tv_code.setClickable(false);//防止重复点击
            tv_code.setText(millisUntilFinished / 1000 + "s");
        }
    }
}
